package top.lishuoboy.cloud.provider.payment8001.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import top.lishuoboy.dependency.base.str.MyStrPool;

import java.util.concurrent.TimeUnit;

/**
 * service直接写类了，懒得写接口了
 *
 * @author lishuoboy
 * @date 2022/4/6 15:49
 */
@Service
public class PaymentService {
    /** 非高并发响应秒回的业务 */
    private String paymentInfoOK() {
        System.out.println("OK");
        return "OK,     线程: " + Thread.currentThread().getName();
    }

    /** 非高并发响应时间较长的业务 */
    // fallbackMethod 指定善后方法名,超时或异常调用方法 paymentInfo_TimeOutHandler()
    @HystrixCommand(
        fallbackMethod = "paymentInfo_TimeOutHandler",
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
        })
    @SneakyThrows
    public String paymentInfoTimeOut() {
        System.out.println("TimeOut");

//        System.out.println(1/0);
        int timeout = 5000;
        TimeUnit.MILLISECONDS.sleep(timeout);
        return "OK,     线程: " + Thread.currentThread().getName() + "   TimeOut, 耗时(秒): " + timeout;
    }

    // 用来善后的方法
    public String paymentInfo_TimeOutHandler() {
        return "线程池:  " + Thread.currentThread().getName() + "  8001系统繁忙或者运行报错，请稍后再试";
    }

    //=====服务熔断
    @HystrixCommand(
        fallbackMethod = "paymentCircuitBreaker_fallback",
        commandProperties = {
            // 所有参数说明见 HystrixCommandProperties.java
            // 默认在10秒滚动窗口内，每当20个请求中，有50%失败时，熔断器就会打开5秒。此时再调用此服务，将会直接返回失败，不再调远程服务。直到5s钟之后，重新检测该触发条件，判断是否把熔断器关闭，或者继续打开
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),                      // 是否开启断路器。默认为 true
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000"),    // 滚动统计窗口。默认为 10秒
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),         // 请求次数。默认20次
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),       // 失败率达到多少后跳闸 ，默认50%
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),    // 休眠时间。默认5秒
        })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException(MyStrPool.LOG_PRE + "id 不能负数哦");
        }
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号: " + IdUtil.simpleUUID();
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return MyStrPool.LOG_PRE + "id 不能负数，请稍后再试。id: " + id;
    }
}